import MySQLdb as db
import os
import json
dbHost = '127.0.0.1'
dbUser = 'root'
dbPasswd = '123456789'
dbName = 'mazda'
conn = db.connect(host=dbHost, user=dbUser, passwd=dbPasswd, db=dbName, port=3306)
cur = conn.cursor(cursorclass=db.cursors.DictCursor)
file = os.path.dirname(__file__) + '/data'
with open(file,'r') as w:
	
	data = w.read()
	data = json.loads(data)
	for x in data:
		sql = "insert into carLine (name,url) values ('{}','{}')".format(x['name'],x['url'])
		back = cur.execute(sql)
		# import ipdb;ipdb.set_trace()
		id = cur.lastrowid
		y = x['chexi']		
		key = y.keys()
		key.remove('mainPart')
		tmp = []
		for t in key:
			tmp.append(y[t])
		key.append('lineId')
		key = ','.join(key)		
		va = "'" + "','".join(tmp) + "'" 
		sql = '''insert into series ({}) values ({},{})'''.format(key,va,id)
		back = cur.execute(sql)
		id = cur.lastrowid
		for x in y['mainPart']:
			for ab in x:
				sql = "insert into topPart (name,seriesId) values ('{}',{})".format(ab,id)
				back = cur.execute(sql)
				id = cur.lastrowid
				for y in x[ab]:
					sql = "insert into mainPart (name,img,topId) values ('{}','{}',{})".format(y['name'],y['img'],id)
					back = cur.execute(sql)
					id = cur.lastrowid
					for x in y['sonPart']:
						key = ','.join(x.keys()) + ',mainId'
						tmp = x.values()
						tmp[-1] = db.escape_string(tmp[-1])
						va = "'" + "','".join(tmp) + "'"
						sql = '''insert into sonPart ({}) values ({},{}) '''.format(key,va,id)
						# print sql
						back = cur.execute(sql)













	
